package com.campus.customer.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 订单超时处理服务
 */
@Service
@Slf4j
public class OrderTimeoutService {

    @Autowired
    private RedisService redisService;
    

    private static final String ORDER_TIMEOUT_QUEUE = "order_timeout_queue";
    private static final int TIMEOUT_MINUTES = 15;

    /**
     * 添加订单到超时队列
     * @param orderId 订单ID
     */
    public void addOrderToTimeoutQueue(String orderId) {
        try {
            // 计算15分钟后的时间戳
            long executeTime = System.currentTimeMillis() + (TIMEOUT_MINUTES * 60 * 1000L);
            
            // 添加到Redis延时队列
            redisService.addDelayTask(ORDER_TIMEOUT_QUEUE, orderId, executeTime);
            
            log.info("订单 {} 已添加到超时队列，将在{}分钟后检查", orderId, TIMEOUT_MINUTES);
        } catch (Exception e) {
            log.error("添加订单到超时队列失败: {}", orderId, e);
        }
    }

    /**
     * 从超时队列中移除订单（支付成功时调用）
     * @param orderId 订单ID
     */
    public void removeOrderFromTimeoutQueue(String orderId) {
        try {
            Long removed = redisService.removeDelayTask(ORDER_TIMEOUT_QUEUE, orderId);
            if (removed > 0) {
                log.info("订单 {} 已从超时队列中移除", orderId);
            } else {
                log.warn("订单 {} 在超时队列中不存在或已被处理", orderId);
            }
        } catch (Exception e) {
            log.error("从超时队列移除订单失败: {}", orderId, e);
        }
    }


}